function XMPPClient() {
    /** 
     * @type Xmpp4Js.Connection
     */
    this.con = null;
}

XMPPClient.prototype = {
    CHAT_OPTIONS : {
        ignoreResource: true,
        ignoreThread: true
    },

    /**
     * Connect and set handler that will attempt login
     */
    login: function(username, password, domain, resource, endpoint, registerMe) {
        
        // store this for onConnectForLogin
        this.username = username;
		this.password = password;
		this.domain = domain;
		this.resource = resource;
		this.endpoint = endpoint;
		this.registerMe = registerMe;
        
		//Test
		//this.register();
		//return false;
		
        // set up the connection
        this.init();
        
        // set a listener to call onConnectForLogin once when connected
        this.con.on("connect", this.onConnectForLogin, this, {single: true} );
        
        this.con.connect( this.domain);
        
        //this.logMessage( "Connecting..." );
        
        // return false so the form doesn't submit
        return false;
    }, 
	
	register: function(username, password, domain, resource, endpoint, registerMe) {
		//this.loginForm = form;
		
		this.username = username;
		this.password = password;
		this.domain = domain;
		this.resource = resource;
		this.endpoint = endpoint;
		this.registerMe = registerMe;
		
		this.init();
		this.con.on("connect", this.onConnectForRegister, this, {single:true});
		
		this.con.connect(this.domain);
		
		this.logMessage("Registering...");
		return false;
	},
	
	onConnectForRegister: function() {
		this.logMessage("Connected, now trying to register...");
		
		//var domain = this.loginForm.domain.value;
        //var username = this.loginForm.username.value;
        //var password = this.loginForm.password.value;
		
		var registrationFlow = new Xmpp4Js.Workflow.Registration({
			con:this.con,
			listeners: {
				scope:this,
				success: this.onRegCompleted,
                failure: this.onRegError
			}
		});
		
		var fields = new Array();
		fields["username"] = this.username;
		fields["password"] = this.password;
		//fields["email"] = "m@m.com";
		registrationFlow.start(fields);
		
		this.logMessage("Registration is now over!");
	},
	
	onRegCompleted: function() {
		//this.con.send(this.con.getPacketHelper().createPresence());
		this.logMessage("Registration Completed successfully!");
		
		this.onConnectForLogin();
	},
	
	onRegError: function() {
		this.logMessage("Registration encountered an error, try again!");
	},
    
    close: function() {
        this.con.close();
        
        // return false so the form doesn't submit
        return false;
    },

    sendMessage: function(to, messageText) {
                
        var msgPacket = new Xmpp4Js.Packet.Message( to, "chat", messageText );
        
        this.con.send( msgPacket );
        
        //this.logMessage( this.con.getJid().toString()+": "+messageText);
        
        // return false so the form doesn't submit
        return false;
    },
    
    /**
     * Display a message.
     */
    logMessage: function(msg) {
        alert(msg);
		//window.status = msg;
    },
    
    
    /**
     * Initialize the connection
     *
     * @private
     */
    init: function() {
        var stanzaProvider = new Xmpp4Js.Packet.StanzaProvider();
        stanzaProvider.registerDefaultProviders();
        
        var connectionConfig = {
            // FIXME none of this transport stuff should be needed if we plan to resume.
            transport: {
                useKeys: true,
                
                clazz: Xmpp4Js.Transport.Script ,
                endpoint: this.endpoint // where your BOSH server is running.
            },
            stanzaProvider: stanzaProvider,
            listeners: {
                scope : this,
                error : this.onError,
                close : this.onClose
            }
        }

        this.con = new Xmpp4Js.Connection(connectionConfig);
        
        this.chatManager = Xmpp4Js.Chat.ChatManager.getInstanceFor( this.con );
        this.chatManager.setOptions(this.CHAT_OPTIONS);

        this.chatManager.on({
            scope : this,
            chatStarted : this.onChatStarted,
            messageReceived : this.onChatMessageReceived
        });
    },
	
    /**
     * This is called when we connect. It performs a login.
     * @private
     */
    onConnectForLogin: function() {
        
        // start the login flow
        var loginFlow = new Xmpp4Js.Workflow.Login({
            con: this.con,
            listeners: {
                scope: this,
                success: this.onLoginCompleted,
                failure: this.onAuthError
            }
        });

        //this.logMessage( "Loggin in..." );

        var type = this.username ? "plaintext" : "anon";
        loginFlow.start( type, this.username, this.password, this.resource );
    },
    
    /**
     * We're now authenticated
     * @private
     */
    onLoginCompleted : function() {
        
        // send the initial presence packet.
        this.con.send(this.con.getPacketHelper().createPresence());
        
        //this.logMessage( "Logged in." );
    },
    
    /**
     * 
     * @private
     */
    onAuthError: function() {
        this.logMessage( "There was authentication error. Try again." );
		
		if(this.username == '0' || this.password=='0')
		{
			return;
		}
		
		if(this.registerMe)
		{
			this.onConnectForRegister();
		}
		//this.register();
    },
    
    /**
     * @private
     */
    onError : function( isTerminal, packetNode, title, message ) {
        this.logMessage( "There was an error(fatal="+isTerminal+"): "+message );
    },
    
    /**
     * 
     * @private
     */
    onClose : function( con ) {
        //this.logMessage( "Connection to "+this.con.domain+" closed." );
 
        // clean house.
        delete this.con;
    },
    
    /**
     * 
     * @private
     */
    onChatStarted : function(chat) {
        //this.logMessage( "Chat with " + chat.getParticipant().toString() + " started" );
    },
    
    /**
     * 
     * @private
     */
    onChatMessageReceived : function(chat, messagePacket) {
        if( messagePacket.hasContent() ) {
		    rpcxmpp.dispatch(messagePacket.getBody(), messagePacket.getFrom());
            //this.logMessage( messagePacket.getFrom() + ": " + messagePacket.getBody() );
        } 
        
        // else, some extension sending a message.
    }
}

var client = null;
client = new XMPPClient();